package com.sina.shop.controller;

import com.github.pagehelper.PageHelper;
import com.sina.shop.dao.PersonDao;
import com.sina.shop.model.Person;
import com.sina.shop.tool.ApiBody;
import com.sina.shop.tool.Validator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/person")


public class PersonController extends BaseController {

    @Autowired
    private PersonDao personDao;

    /**
     * 查询所有用户信息
     * @param page
     * @param size
     * @return ApiBody
     **/
    @GetMapping("/list")
    public ApiBody list(@RequestParam(value = "page", defaultValue = "1") int page, @RequestParam(value = "size", defaultValue = "10") int size) {
        //分页查询
        int currentPage = page == 0 ? 1 : page;
        int pageSize = size == 0 ? 10 : size;
        int offset = (page - 1) * size;
        List<Person> personList = personDao.selectAll(offset, pageSize);
        return apiResult.success("获取成功了",personList);
    }
    /**
     * 根据id查询用户信息
     * @param id
     * @return ApiBody
     */
    @GetMapping("/{id}")
    public ApiBody get(@PathVariable("id") int id) {
        Person person = personDao.selectByPrimaryKey(id);
        return apiResult.success("success",person);
    }

    /**
     * 新增用户信息
     * @param person
     * @return ApiBody
     */
    @PostMapping("/add")
    public ApiBody add(Person person) {
        System.out.println(person);
        //验证用户名是否为空
        if (person.getUsername() == null || person.getUsername().trim().equals("")) {
            return apiResult.error("用户名不能为空");
        }
        //验证邮箱是否为空
        if (person.getEmail() == null || person.getEmail().trim().equals("")) {
            return apiResult.error("邮箱不能为空");
        }
        //验证邮箱格式是否正确
        if (Validator.isValidEmail(person.getEmail()) == false) {
            return apiResult.error("邮箱格式不正确");
        }
        //验证用户名是否重复
        Person personDetail = personDao.selectByUsername(person.getUsername());
        if (personDetail != null) {
            return apiResult.error("添加失败，用户名已存在，请更换用户名");
        }
        int result = personDao.insert(person);
        if (result == 0) {
            return apiResult.error("新增失败");
        }
        return apiResult.success("新增成功",person);
    }

    /**
     * 删除用户信息
     * @param id
     * @return ApiBody
     */
    @DeleteMapping("/{id}")
    public ApiBody delete(@PathVariable("id") int id) {
        int result = personDao.deleteByPrimaryKey(id);
        if (result == 0) {
            return apiResult.error("删除失败");
        }
        return apiResult.success("删除成功");
    }



}
